import promisify from './libs/api-promise';
import mock_data from './data.js'
/** 以上引入了公共库，作用是：
 * promisify: 提供 Promise 化的 API，通过 tt.promises.API_NAME 使用
 */

function init() {
  promisify();
}

Block({
  data: {
    block_title: "昆仑小智智能体",
    appId:"cli_a65313718678d365",
    base_url: "https://xz.klszkj.com:9000/botapi/api",
    info: '',
    height: 0,
    newImageSrc:"images/new.png",
    app_list:[

    ],
    scrollTop: 0,
    grid_number: 8,
    containerHeight:0
  },
  onLoad(options) {
    // Block 加载完成
    init();
    // 通过 options 可以拿到宿主信息和 BlockInfo
    // console.log(options.host, options.blockInfo);

   
    // 监听 Block 的容器尺寸
    tt.onContainerResize(({ width, height}) => {
       let grid_number = this.data.grid_number
        if(width < 600){
          grid_number=4
        }else if(width < 780){
          grid_number=5
        }else{
          grid_number=8
        }
        this.setData({
            grid_number,
            containerHeight: height
        })
    })
  },
  async onReady() {
    // Block 首次渲染完成
    const rect = await tt.promises.getContainerRect();

    this.setData({
      llm_base_url: `${this.data.base_url}/llm/v1`,
    });
    
    let grid_number = this.data.grid_number
    if(rect.width < 600){
      grid_number=4
    }else if(rect.width < 780){
      grid_number=5
    }else{
      grid_number=8
    }
     this.setData({
            grid_number,
            containerHeight: rect.height
        })
    this.methods.login()
  },
  onShow() {
    // Block 显示
  },
  onHide() {
    // Block 隐藏
  },
  onDestroy() {
    // Block 被销毁
  },
  onActivate(state) {
    // 激活的生命周期
    // 激活时可以获取到上次失活保存的数据
    init();
    this.setData(state);
  },
  onInactivate() {
    // 失活的生命周期
    // 失活时这里将 data 数据临时保存起来
    tt.saveState({
      state: this.data,
    });
  },
  onResourceChange(sourceData) {
    // 数据协同接收到的数据
    console.log(sourceData);
  },
  methods: {
    async request(url, method="GET",params={},header={}) {
      const response = await tt.promises.request({ 
        "url": url, 
        "data": params,
        "header": header,
        "method": method,
        "dataType": "json",
        "responseType": "text",
      });
  
      return response
    },
    async getUserInfo() {
      const { code } = await tt.promises.login();
      const { userInfo } = await tt.promises.getUserInfo();

      this.setData({
        userInfo,
        code
        // info: JSON.stringify({
        //   code,
        //   userInfo,
        // }, null, 2),
      });
    },
    async getSystemInfo() {
      const systemInfo = await tt.promises.getSystemInfo();

      this.setData({
        info: JSON.stringify(systemInfo, null, 2),
      });
    },
    async getContainerRect() {
      const rect = await tt.promises.getContainerRect()
      this.setData({
        info: JSON.stringify(rect, null, 2)
      })

    },
    login(){
      let me = this
      let url=`${this.data.base_url}/sys/auth/login`
      let loginParams = {
            "logonWay": 5,
            // appId:"cli_a621920e3038d366"
            "appId": this.data.appId
        }
      //  let header = {

      //  }
        this.methods.getUserInfo().then(()=> {
          loginParams.code = this.data.code
          me.methods.request(url,"POST",loginParams,{}).then(res => {
                  if(res.data.ok && res.data.data.token){
                    this.methods.getUserAppList(res.data.data.token)
                    this.setData({
                      token: res.data.data.token
                    })
                  }else{
                    this.setData({err_info:"服务貌似开小差了！"})
                  }
                 // 关闭 Block 的 Loading，当 useStartLoading=true 时有效
                tt.hideBlockLoading();
                })
        })
    },
    getUserAppList(token){
      let me  = this
      let url = `${this.data.llm_base_url}/app/user-app-info`
      
      if(!token) token = this.data.token
      let header = {
        "Token": token
      }
      this.methods.request(url,"GET",{},header).then(res => {
        if(res.data.ok){
          this.methods.generateListLayout(res.data.data)
        }else{
          this.setData({err_info:"服务貌似开小差了！"})
        }
        // me.methods.showToast()
      }).catch(err=> console.error(err))
    },
    generateListLayout(app_info){
      if(app_info.apps && app_info.apps.length > 0){
        let app_list = app_info.apps,categories = app_info.categories
        let empty_category_list = app_list.filter(a => a.categories.length==0 || !a.categories)
        let json_list=[{name:"其他应用", apps:empty_category_list}]
        categories.forEach(c => {
          let list = app_list.filter(a => a.categories.includes(c))
          json_list.unshift({name: c, apps: list})
        })
        // let json_list = [{type: 1, name:"聊天应用", apps:[]},{type: 2, name:"文本生成", apps:[]},{type: 3, name:"Agent", apps:[]},{type: 4, name:"工作流", apps:[]},{type: -1, name:"网页应用", apps:[]}]
     
        this.setData({
              app_list: json_list,
              err_info: ""
            })
      }
    },
    actions(e){
      // cli_a621920e3038d366
      let uri =  `https://applink.fklzl.cnpc.com.cn/client/web_app/open?appId=cli_a621920e3038d366&path=botapi/chat/${e.currentTarget.dataset.appId}`
      uri=`https://applink.fklzl.cnpc.com.cn/client/web_app/open?appId=cli_a621920e3038d366&mode=appCenter&reload=false&lk_target_url=https%3A%2F%2Fopen.fklzl.cnpc.com.cn%2Fopen-apis%2Fauthen%2Fv1%2Findex%3Fapp_id%3Dcli_a621920e3038d366%26redirect_uri%3Dhttps%253A%252F%252Fxz.klszkj.com%253A9000%252Fbotapi%252F%253FappId%253Dcli_a621920e3038d366%2526question%253D%2526path%253D%252Fchat%252F${e.currentTarget.dataset.appId}%2526state%253DRANDOMSTATE`
     
      tt.openSchema({
        schema: uri,
        external: false,
        success(res) {
          console.log(JSON.stringify(res));
        },
        fail(res) {
          console.log(`openSchema fail: ${JSON.stringify(res)}`);
        }
      });
    },
    showToast() {
      tt.showToast({
        title: 'show toast success',
        icon: 'success',
        duration: 1500,
        success(res) {
          console.log('showToast 调用成功', res.errMsg);
        },
        fail(res) {
          console.log('showToast 调用失败', res.errMsg);
        },
        complete(res) {
          console.log('showToast 调用结束', res.errMsg);
        }
      });
    }
  }
});
